import uuid from 'uuid';
import insert from './atom/db/insert';
import query from './atom/db/query';
import { IBaseTable } from './atom/db/interfaces';

declare const action_id: string;
declare const session_id: string;
declare const spaceid: string;

interface Message {
	no: string;
	staff_number: string;
	name: string;
	confirm_date: string;
	effectivedate: string;
	staus: string;
	purchase_right: string;
	enddate: string;
	org_name: string;
	memo: string;
	accessory_url: string;
	certificate: string;
}

interface teachStaff extends IBaseTable {
	staff_number: string;
	staff_name: string;
	deptid: string;
	deptname: string;
}

async function atom(msg: Message) {
	const systemid = '6051';

	const q = query(action_id, session_id, spaceid, systemid);
	q.prepare('teach_staff', ['staff_name', 'staff_number', 'deptid', 'deptname'], { staff_number: msg.staff_number }, 1, 1);
	const [teach_data] = await q.exec();
	if (teach_data.length > 0) {
		const teach_info = teach_data[0] as teachStaff;
		const { exec, prepare } = insert(action_id, session_id, spaceid, systemid);
		const effectivedate = (msg.effectivedate === '0') ? 0 : (new Date(msg.effectivedate).getTime());
		const enddate = (msg.enddate === '0') ? 0 : (new Date(msg.enddate).getTime());
		prepare('certifi_info', [{ _id: uuid(), no: msg.no, staff_name: teach_info.staff_name, staff_number: teach_info.staff_number, deptid: teach_info.deptid, deptname: teach_info.deptname, name: msg.name, confirm_date: new Date(msg.confirm_date).getTime(), effectivedate: effectivedate, staus: msg.staus, purchase_right: msg.purchase_right, enddate: enddate, org_name: msg.org_name, memo: msg.memo, accessory_url: msg.accessory_url, certificate: msg.certificate }]);
		const res = await exec();
		if (res.code === 1) {
			return 'success';
		} else {
			return 'fail';
		}
	} else {
		return 'fail';
	}
}